package com.eqxiu.ieditor.homepage.controller;

import com.alibaba.fastjson.JSON;
import com.eqxiu.ieditor.api.HomePageUserServiceApi;
import com.eqxiu.ieditor.api.controller.BaseApiController;
import com.eqxiu.ieditor.api.controller.common.StringUtils;
import com.eqxiu.ieditor.commons.web.ResultData;
import com.eqxiu.ieditor.dto.HomePageUserDTO;
import com.eqxiu.user.api.UserApi;
import com.eqxiu.user.api.dto.User;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName HomePageUserController
 * @escription 微主页用户信息入口
 * @Author suixiangyu
 * @Date 2019/4/310:08 AM
 */
@Controller
@Api(description = "微主页用户信息入口")
public class HomePageUserController implements BaseApiController {

    private final Logger LOGGER = LoggerFactory.getLogger(HomePageUserController.class);

    @Autowired
    private HomePageUserServiceApi homePageUserServiceApi;

    @Autowired
    private UserApi userApi;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * @return com.eqxiu.ieditor.commons.web.ResultData
     * @Description 保存微主页用户信息
     * @Author SuiXiangyu
     * @Date 2019/4/3
     * @Param [homePageUserDTO]
     **/
    @PostMapping("api/homepage/save-user-message")
    @ApiOperation(value = "保存微主页用户信息(更新通用)")
    @ResponseBody
    public ResultData saveHomePageUserMessage(HomePageUserDTO homePageUserDTO) {
        //基础信息校验
        LOGGER.info("开始保存了");
        if ("".equals(homePageUserDTO.getUserId())) {
            return fail().setMsg("userid can not be null");
        }
        String redisKey = "getHomePageUserMessage:" + homePageUserDTO.getUserId();
        try {
            //获取基础用户信息
            User user = userApi.getUser(homePageUserDTO.getUserId());
            homePageUserDTO.setLoginId(user.getLoginName());
            homePageUserDTO.setPhone(user.getPhone());
            homePageUserDTO.setLoginTime(new Date());
            homePageUserDTO.setUpdateTime(new Date());
            String nickName= StringUtils.removeNonBmpUnicode(homePageUserDTO.getNickName());
            homePageUserDTO.setNickName(nickName);
            String homePageName= StringUtils.removeNonBmpUnicode(homePageUserDTO.getHomePageName());
            homePageUserDTO.setHomePageName(homePageName);
            LOGGER.info("保存的数据"+JSON.toJSONString(homePageUserDTO));
            homePageUserServiceApi.addHomePageUserMessage(homePageUserDTO);
            //更新时清除redis
            if (redisTemplate.opsForValue().size(redisKey) != null || redisTemplate.opsForValue().size(redisKey) > 0) {
                redisTemplate.delete(redisKey);
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            return fail().setMsg("homepage user add error");
        }
        return success();
    }

    /**
     * @return com.eqxiu.ieditor.commons.web.ResultData
     * @Description 获取微主页用户信息
     * @Author SuiXiangyu
     * @Date 2019/4/3
     * @Param [homePageUserDTO]
     **/
    @PostMapping("api/homepage/get-user-message")
    @ApiOperation(value = "获取微主页用户信息 必传userId")
    @ResponseBody
    public ResultData getHomePageUserMessage(String userId) {
        String redisKey = "getHomePageUserMessage:" + userId;
        if (userId == null) {
            return fail().setMsg("userid can not be nul");
        }
        if (redisTemplate.opsForValue().size(redisKey) == null || redisTemplate.opsForValue().size(redisKey) == 0) {
            HomePageUserDTO backHomePageUserDTO = new HomePageUserDTO();
            try {
                backHomePageUserDTO = homePageUserServiceApi.queryHomePageUserMessage(userId);
                if (backHomePageUserDTO != null) {
                    User user = userApi.getUser(userId);
                    backHomePageUserDTO.setHeadImg(user.getHeadImg());
                }
            } catch (Exception e) {
                LOGGER.error(e.getMessage());
                return fail().setMsg("homepage user error").setObj(backHomePageUserDTO);
            }
            if (backHomePageUserDTO != null) {
                redisTemplate.opsForValue().set(redisKey, new Gson().toJson(backHomePageUserDTO), 24, TimeUnit.HOURS);
            }
            return success().setObj(backHomePageUserDTO);

        } else {
            String s = redisTemplate.opsForValue().get(redisKey);
            HomePageUserDTO backHomePageUserDTO = new HomePageUserDTO();
            backHomePageUserDTO = new Gson().fromJson(s, HomePageUserDTO.class);
            return success().setObj(backHomePageUserDTO);
        }
    }
}
